package cn.da.shuai.cool.system.service.service.impl;

import cn.da.shuai.cool.system.service.mapper.CoolRoleMenuMapper;
import cn.da.shuai.cool.system.service.mapper.CoolUserRoleMapper;
import cn.da.shuai.cool.system.model.entity.role.CoolRoleMenu;
import cn.da.shuai.cool.system.model.entity.role.CoolUserRole;
import cn.da.shuai.cool.system.service.service.ICoolPermissionService;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@AllArgsConstructor
public class CoolPermissionServiceImpl implements ICoolPermissionService {

    private final CoolRoleMenuMapper coolRoleMenuMapper;

    private final CoolUserRoleMapper coolUserRoleMapper;

    @Override
    public List<Integer> getRoleMenus(Integer roleId) {
        if (roleId == null) {
            return List.of();
        }
        LambdaQueryWrapper<CoolRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(CoolRoleMenu::getMenuId)
                .eq(CoolRoleMenu::getRoleId, roleId);
        return coolRoleMenuMapper.selectObjs(wrapper);
    }

    @Override
    public void assignRoleMenus(Integer roleId, List<Integer> menuIds) {
        if (roleId == null || CollectionUtil.isEmpty(menuIds)) {
            return;
        }
        List<CoolRoleMenu> coolRoleMenus = new ArrayList<>(menuIds.size());
        for (Integer menuId : menuIds) {
            coolRoleMenus.add(new CoolRoleMenu(roleId, menuId));
        }

        coolRoleMenuMapper.insert(coolRoleMenus);
    }

    @Override
    public List<Integer> getUserRoles(Integer userId) {
        if (userId == null) {
            return List.of();
        }
        LambdaQueryWrapper<CoolUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(CoolUserRole::getRoleId)
                .eq(CoolUserRole::getUserId, userId);
        return coolUserRoleMapper.selectObjs(wrapper);
    }

    @Override
    public void assignUserRoles(Integer userId, List<Integer> roleIds) {
        if (userId == null || CollectionUtil.isEmpty(roleIds)) {
            return;
        }
        List<CoolUserRole> coolRoleMenus = new ArrayList<>(roleIds.size());
        for (Integer roleId : roleIds) {
            coolRoleMenus.add(new CoolUserRole(userId, roleId));
        }

        coolUserRoleMapper.insert(coolRoleMenus);
    }
}
